<template>
<div class="container">
<!-- 右上角导航栏 -->
    <NavBar @view-history-questionnaire="viewHistoryQuestionnaire" />
  <div class="message-container">
  
    <!-- 左侧聊天列表 -->
    <div class="chat-list">
      <div 
        v-for="chat in chatList" 
        :key="chat.id"
        class="chat-item"
        :class="{ active: activeChat && activeChat.id === chat.id }"
        @click="selectChat(chat)"
        :style="{ animation: chat.hasNewMsg ? 'flash 1s' : '' }"
      >
        <div class="user-info">
          <span>{{ chat.name }}</span>
          <span v-if="chat.unread > 0" class="unread-badge">{{ chat.unread }}</span>
        </div>
      </div>
    </div>

    <!-- 右侧聊天窗口 -->
    <div class="chat-window">
      <div v-if="activeChat" class="chat-history">
        <div v-for="(msg, index) in messages" :key="index">
        <!-- 系统消息单独处理 -->
          <div v-if="msg.isSystem" class="system-alert">
            {{ msg.content }}
          </div>
          <!-- 普通消息 -->
          <div v-else 
            class="message-bubble"
            :class="{ 
            'self': msg.isSelf,
            'other': !msg.isSelf
            }"
          >
          <div class="content">
            {{ msg.content }}
            <!-- 仅咨询师可见情绪 -->
            <span v-if="msg.showEmotion" class="mood-indicator">
              {{ msg.emotion === 'POSITIVE'? '😄':'😡' }}
            </span>
          </div>
          <span class="time">发送于：{{ formatTime(msg.timestamp) }}</span>
         </div>
        </div>
      </div>
      <div class="message-input">
        <textarea 
          v-model="newMessage"
          @keyup.enter="sendMessage"
          placeholder="输入消息..."
        ></textarea>
        <button @click="toggleEmojiPicker">😀</button> <!-- 表情选择按钮 -->
        <button @click="sendMessage">发送</button>
        <!--表情选择器-->
        <div v-if="showEmojiPicker" class="emoji-picker">
      <span 
        v-for="emoji in emojis" 
        :key="emoji"
        @click="insertEmoji(emoji)"
      >
        {{ emoji }}
      </span>
      </div>
      </div>
    </div>
  </div>
</div>
</template>

<script>
import NavBar from './NavBar.vue'; // 引入导航栏组件
//import * as echarts from 'echarts'; //折线图
export default {
  components: {
    NavBar
  },
  data() {
    return {
      chatList: [],
      activeChat: null,
      messages: [],
      newMessage: '',
      ws: null,
      currentUserId: localStorage.getItem('userId'),
      role: localStorage.getItem('role'),
      pollingInterval: null,
      reconnectAttempts: 0,
      showEmojiPicker: false, 
      emojis: ['😀', '😃', '😄', '😁', '😆', '😅', '😂', '🤣', '😊', '😇',
               '🙂', '🙃', '😉', '😌', '😍', '🥰', '😘', '😗', '😙', '😚', 
               '😋', '😛', '😝', '😜', '🤪', '🤨', '🧐', '🤓', '😎', '🤬', 
               '🤩', '🥳', '😏', '😒', '😞', '😔', '😟', '😕', '🙁', '☹️', 
               '😣', '😖', '😫', '😩', '🥺', '😢', '😭', '😤', '😠', '😡'], // 表情列表
      emotionHistory: [],  // 存储最近20条情绪记录
      hintStates: {        // 提示状态记录
      positive: false,
      negativeSingle: false,
      negativeCritical: false,
      lastHintTime: null,
      hintStates: {
      negativeSingle: false, // 单次消极提示
      negativeCritical: false // 临界值提示
    }
    }
  }
  },
  created() {
    this.initWebSocket()
    this.loadChatList()
    this.startPollingUnread()
    this.checkRouteParams()
  },
  beforeUnmount() {
    if (this.pollingInterval) {
      clearInterval(this.pollingInterval)
    }
    if (this.ws) {
      this.ws.close()
    }
  },
  methods: {
    formatTime(timestamp) {
    if (!timestamp) return '';
    const date = new Date(timestamp);
    const year = date.getFullYear(); // 年
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月（补零）
    const day = String(date.getDate()).padStart(2, '0'); // 日（补零）
    const hours = String(date.getHours()).padStart(2, '0'); // 时（补零）
    const minutes = String(date.getMinutes()).padStart(2, '0'); // 分（补零）
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  },
    // 检查路由参数
    async checkRouteParams() {
      await this.$nextTick()
      let targetId = null;
      if(this.role === 'VISITOR'){
        targetId = this.$route.query.targetId
      }else{
        targetId = localStorage.getItem("currentConsultantId")
      }
      console.log("targetId", targetId)
      if (targetId && !this.chatList.some(c => c.id == targetId)) {
        this.addNewChat(targetId)
      }
    },
    // 修改后的方法：添加新会话至左侧栏
    addNewChat(targetId) {
      const nickname = localStorage.getItem(targetId) // 从 localStorage 中获取咨询师昵称
      console.error("nickname",nickname)
      if (nickname) {
        this.chatList.unshift({
          id: targetId,
          name: nickname, // 使用 localStorage 中的昵称
          hasNewMsg: true,
          unread: 1,
          partnerId: targetId,
          userId: this.currentUserId
        })
      } else {
        console.error('未找到咨询师昵称，请确保已正确存储咨询师信息')
      }
    },
    initWebSocket() {
      const reconnect = () => {
      if (this.reconnectAttempts > 5) return
      this.reconnectAttempts++
      setTimeout(() => this.initWebSocket(), Math.min(1000 * this.reconnectAttempts, 5000))
    }
      this.ws = new WebSocket(`ws://localhost:8080/ws/chat?userId=${this.currentUserId}`)

      
    this.ws.onopen = () => {
      console.log("websocket消息建立成功！")
      this.reconnectAttempts = 0;
    };

    this.ws.onclose = (e) => {
      if (e.code !== 1000) { // 非正常关闭
       reconnect();
     }
   };

    this.ws.onerror = (error) => {
      console.error('WebSocket error:', error)
      this.ws.close()
    };
    // 页面可见性监听
    document.addEventListener('visibilitychange', () => {
      if (document.visibilityState === 'visible' && !this.ws) {
        this.initWebSocket()
      }event.data
    });
    if(this.role === "VISITOR"){
      this.ws.onmessage = (event) => {
        try{
        const baseMsg = JSON.parse(event.data);
        this.handleIncomingMessage(baseMsg)
        }catch(error){
          console.error("msg解析失败")
          console.error('原始数据:', event.data);
        }
      };
    }
    },
   // 修改后的加载会话列表方法，调session，但是可能还需要加返回字段
    async loadChatList() {
      try {
        const response = await this.$axios.get('/chat/session', {
          headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
        })
        this.chatList = response.data.map(chat => {
          const otherId = chat.userId == this.currentUserId ? chat.partnerId : chat.userId
          console.error("这里的nickname为：",chat.nickName)
          const nickname = chat.nickName // 从 localStorage 中获取咨询师昵称
          return {
            id: otherId,
            name: nickname || '未知用户', // 使用 localStorage 中的昵称
            hasNewMsg: false,
            unread: 0,
            userId: chat.userId,
            partnerId: chat.partnerId
          }
        })
        if (this.chatList.length > 0 && !this.$route.query.targetId) {
          this.selectChat(this.chatList[0])
        }
      } catch (error) {
        console.error('加载会话列表失败:', error)
      }
    },
   async selectChat(chat) {
  if (!chat) {
    console.error("chat对象为空");
    return;
  }
  // 清空旧数据
  this.messages = []; 

  // 清除旧轮询
  if (this.pollingInterval) {
    clearInterval(this.pollingInterval);
    this.pollingInterval = null;
  }

  // 锁定当前chatId
  const currentChatId = chat.id;
  console.error("currentChatId为：",currentChatId)
  localStorage.setItem("currentConsultantId", currentChatId);

  // 重置状态
  this.emotionHistory = [];
  this.hintStates = {
    negativeSingle: false,
    negativeCritical: false
  };
  this.activeChat = chat;
  chat.hasNewMsg = false;

  // 立即加载一次历史记录
  await this.loadChatHistory(currentChatId);

  // 智能轮询（防重复+消息合并）
  let isProcessing = false;
  this.pollingInterval = setInterval(async () => {
    if (!isProcessing && this.activeChat?.id === currentChatId) {
      isProcessing = true;
      try {
        await this.loadChatHistory(currentChatId);
      } finally {
        isProcessing = false;
      }
    }
  }, 3000);
},

// 专用加载历史记录
async loadChatHistory(chatId) {
  console.error("chatId为：",chatId)
  try {
    const response = await this.$axios.post('/chat/chatHistory', 
      { receiverId: chatId },
          {
            headers: {
              Authorization: `Bearer ${localStorage.getItem('token')}`,
              'Content-Type': 'application/json; charset=utf-8'
            }
          }
    );
    // 智能消息合并（保留系统消息）
    const newMessages = response.data.map(msg => (
     //  console.log("isSelf的：",msg.senderId === Number(this.currentUserId)),
       {
      ...msg,
      timestamp: new Date(msg.timestamp),
      isSelf: String(msg.senderId) === this.currentUserId,
      showEmotion: this.role === 'CONSULTANT' && msg.emotion
    })).sort((a, b) => a.timestamp - b.timestamp);

    

    // 使用 Set 去重
    const existingIds = new Set(this.messages.map(m => m.id));
    const mergedMessages = [
      ...this.messages, // 保留所有现有消息
      ...newMessages.filter(msg => !existingIds.has(msg.id))
    ].sort((a, b) => a.timestamp - b.timestamp);

    // 正确更新消息（保留系统消息）
    this.messages = mergedMessages;

    // 触发情绪分析（仅分析新消息）
    this.analyzeRecentEmotions(newMessages);

    // 滚动优化
    this.$nextTick(() => {
      const container = this.$el.querySelector('.chat-history');
      if (container) {
        container.scrollTop = container.scrollHeight + 100;
      }
    });
  } catch (error) {
    console.error('加载聊天记录失败:', error);
  }
},
    // 新增方法：轮询未读消息
    startPollingUnread() {
      this.pollingInterval = setInterval(async () => {
        try {
          const response = await this.$axios.get('/chat/unread', {
            headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
          })
          // 过滤超过7天的未读消息
          const filteredUnread = response.data.data.filter(item => {
          const msgDate = new Date(item.timestamp);
          const now = new Date();
          const diffInDays = Math.floor((now - msgDate) / (1000 * 60 * 60 * 24));
          return diffInDays <= 7; // 仅保留7天内的未读消息
         });
         // 更新未读消息数量
         filteredUnread.forEach(item => {
          const chat = this.chatList.find(c => c.id == item.senderId);
          if (chat) chat.unread = item.count;
         });

          this.$store.commit('messages/UPDATE_UNREAD', response.data.unRead[0])
          
        } catch (error) {
          console.error('获取未读消息失败:', error)
        }
      }, 3000)
    },
    toggleEmojiPicker() {
      this.showEmojiPicker = !this.showEmojiPicker; // 切换表情选择器显示状态
    },
    insertEmoji(emoji) {
      this.newMessage += emoji; // 将表情插入输入框
      this.showEmojiPicker = false; // 插入后关闭表情选择器
    },
    sendMessage() {
        console.log("当前角色 ",this.role);
        console.log("聊天对象: ",this.activeChat);
      const msg = {
        senderId: this.currentUserId,
        receiverId: this.activeChat.id,
        content: this.newMessage.trim(),
        status: 'SENT'
      }
      console.log('WebSocket 状态:', msg.senderId);
      console.log('WebSocket 状态:', msg.receiverId);
      console.error("这里的消息为：",JSON.stringify(msg))
      this.ws.send(JSON.stringify(msg))
     // this.messages.push({ ...msg, isSelf: true, timestamp: new Date() })
      this.newMessage = ''
      this.$nextTick(() => {
         const chatHistory = this.$el.querySelector('.chat-history');
        if (chatHistory) {
         chatHistory.scrollTop = chatHistory.scrollHeight;
      }
    });
    },
    // 修改后的消息处理,创建新聊天人
    handleIncomingMessage(msg) {
      console.error("要发送的消息为： ",msg)
      // 检查消息内容是否为空
     if (!msg.content) {
      console.error('收到空消息:', msg);
      return;
    }
      const isVisitor = this.role === 'VISITOR'
      const senderId = isVisitor ? msg.senderId : msg.receiverId
      let targetChat = this.chatList.find(c => c.id === senderId)

      if (!targetChat) {
        console.error("senderId为：",this.currentUserId)
        console.error("这里的nickname为：",localStorage.getItem("currentConsultantId"))
        const nickname = localStorage.getItem("currentConsultantId") // 从 localStorage 中获取咨询师昵称
        if (nickname) {
          const newChat = {
            id: senderId,
            name: nickname, // 使用 localStorage 中的昵称
            hasNewMsg: true,
            unread: 1,
            userId: this.currentUserId,
            partnerId: senderId
          }
          this.chatList.unshift(newChat)
        //  this.messages.push(msg) 
        } else {
          console.error('未找到用户昵称，请确保已正确存储用户信息')
        }
        return
      }

      if (this.activeChat?.id !== targetChat.id) {
        targetChat.unread++
        targetChat.hasNewMsg = true
      }

      this.messages.push({...msg,timestamp: new Date(msg.timestamp)})
    },
    analyzeRecentEmotions(messages) {
    if (this.role !== 'CONSULTANT') return;

    // 动态计算当前状态（每次分析时重置）
    const currentHints = {
      negativeSingle: false,
      negativeCritical5: false,
      negativeCritical10: false
    };

    // 获取有效情绪数据（排除系统消息）
    const validMessages = messages.filter(m => 
      m.emotion && !m.isSystem && !m.isSelf
    );


    // 提取最近1条和5条情绪
    const [last1] = validMessages.slice(-1);
    const last5 = validMessages.slice(-5);
    const last10 = validMessages.slice(-10);

    // 统计逻辑
    const last1Emotion = last1?.emotion;
    const negativeCount5 = last5.filter(m => m.emotion === 'NEGATIVE').length;
    const negativeCount10 = last10.filter(m => m.emotion === 'NEGATIVE').length;

    // 动态判断提示条件
    currentHints.negativeSingle = last1Emotion === 'NEGATIVE';
    currentHints.negativeCritical5 = negativeCount5 >= 3;
    currentHints.negativeCritical10 = negativeCount10 >= 8;

  if (currentHints.negativeSingle && !this.hintStates.negativeSingle) {
    this.addSystemMessage('系统提示：用户最新消息情绪消极！');
    this.hintStates.negativeSingle = true;
  }
  
  if (currentHints.negativeCritical5 && !this.hintStates.negativeCritical5) {
    this.addSystemMessage('系统提示：用户近期消极情绪较多（5条中有3条以上），需要引起重视！');
    this.hintStates.negativeCritical5 = true;
  } 

  
  if (currentHints.negativeCritical10 && !this.hintStates.negativeCritical10) {
    this.addSystemMessage('警告！！！目前用户情绪现在极度不稳定，如不是正常咨询手段，请立即采取措施！！！');
    this.hintStates.negativeCritical10 = true;

  } 

  // 状态降级处理（当最新消息转为积极时重置）
  if (last1Emotion === 'POSITIVE') {
    this.hintStates.negativeSingle = false;
    if (negativeCount5 < 3) this.hintStates.negativeCritical5 = false;
    if (negativeCount10 < 8) this.hintStates.negativeCritical10 = false;
  }
  },
    // 添加系统消息
    addSystemMessage(text) {
      const isDuplicate = this.messages.some(m => 
    m.isSystem && m.content === text
  );
    if (!isDuplicate) {
      this.messages.push({
        isSystem: true,
        content: text,
        timestamp: new Date(),
        senderId: 'system',
       receiverId: this.currentUserId,
       id: `sys-${Date.now()}` // 添加唯一ID
      });
    }
  
    // 强制滚动到底部
    this.$nextTick(() => {
     const container = this.$el.querySelector('.chat-history');
     if (container) container.scrollTop = container.scrollHeight;
   });
    }
  }
}
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column; /* 改为垂直布局 */
  min-height: 100vh;
}
/* 消息页面样式 */
.message-container {
  display: flex;
  max-height: 85vh;
}

.chat-list {
  width: 250px;
  border-right: 1px solid #ddd;
  overflow-y: auto;
}

.chat-item {
  padding: 15px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  position: relative;
}

.chat-item.active {
  background-color: #f5f5f5;
}

.unread-badge {
  background: red;
  color: white;
  border-radius: 50%;
  padding: 2px 6px;
  font-size: 12px;
  margin-left: 5px;
}

@keyframes flash {
  0% { background-color: rgba(255,0,0,0.1); }
  50% { background-color: rgba(255,0,0,0.3); }
  100% { background-color: transparent; }
}

.chat-window {
  max-height: 80%;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-history {
  display: flex;
  flex-direction: column; /* 确保垂直排列 */
  padding: 20px;
  overflow-y: auto;
  key: auto;
}

.chat-history .message-bubble {
  margin: 10px 0;
  max-width: 20%;
  min-width: 120px; /* 最小宽度 */
  padding: 10px;
  border-radius: 10px;
  background: #e0e0e0;
  display: table; /* 让宽度自适应内容 */
  word-wrap: break-word; /* 长文本自动换行 */
}

.message-bubble.self {
  background: #4D90FE;
  color: white;
  margin-left: auto;/*消息靠右*/
  text-align: left; /* 内容左对齐 */
}

.message-bubble.other {
  background: #ffb6c1;
  margin-right: auto; /*消息靠左*/
  text-align: left; /* 内容左对齐 */
}

/* 确保系统消息样式 */
.message-bubble.system {
  width: 80% !important;
  margin: 10px auto !important;
  background: #fff9c4 !important;
  border: 1px solid #ffe082 !important;
  color: #8a6d3b;
  display: block; /* 改为块级元素 */
}

.mood-indicator {
  font-size: 12px;
  color: #666;
  margin-left: 10px;
}

.message-input {
  padding: 20px;
  border-top: 1px solid #ddd;
  display: flex;
  gap: 10px;
}

.message-input textarea {
  flex: 1;
  height: 60px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}
.emoji-picker {
  display: table; /* 让宽度自适应内容 */
  word-wrap: break-word; /* 长文本自动换行 */
  max-width: 20%;
}
.time {
  font-size: 12px;
}
/* 情绪标识样式 */
.mood-indicator {
  margin-left: 8px;
  font-size: 1.2em;
}

/* 系统提示样式 */
.system-alert {
 width: 80%;
  margin: 20px auto;
  padding: 12px;
  background: #fff9c4;
  border: 1px solid #ffe082;
  border-radius: 8px;
  text-align: center;
  color: #8a6d3b;
  animation: pulse 1.5s ease-in-out;
}

@keyframes pulse {
  0% { transform: scale(0.95); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
}
</style>